import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import {
  ElButton,
  ElMessage,
  ElLink,
  ElRow,
  ElCol,
  ElMessageBox,
  ElTabs,
  ElTabPane,
  ElDescriptions,
  ElDescriptionsItem,
  ElImage,
  ElIcon
} from 'element-plus'
import type {
  ModalType,
  FormValuesType,
  FormValuesTypeDev,
  dimDataType,
  SpanMethodProps
} from './typings'
import { Refresh } from '@element-plus/icons-vue'
import styles from '../../index.module.scss' /** 样式 */
import AliIcon from '../../../../components/AliIocn' /** 阿里巴巴图标库**/
import type { TableColumnProps } from '~/components/ProSaasTable/typings'
import ProSaasTable from '~/components/ProSaasTable'
import DimModel from '../../components/dimModel'
import ChangeGroup from './changeGroup'
import EchartsDim from './echartsDim'
import EchartsEnergy from './echartsEnergy'
import useVuexGetters from '~/hooks/useVuexGetters'
import useWebsocket from '~/hooks/useWebsocket'
import NoticeMes from '../../components/noticeMes'

import callDataSrc from '~/assets/singleLamp/callData.png'
import dimLightSrc from '~/assets/singleLamp/dim.png'
import openLightSrc from '~/assets/singleLamp/open.png'
import closeLightSrc from '~/assets/singleLamp/close.png'
import changeGroupSrc from '~/assets/singleLamp/changeGroup.png'
export default defineComponent({
  props: ['cancel', 'initLamppostTree'],
  setup(props, { expose }) {
    const store = useStore()
    const state = reactive<ModalType>({
      lamppostInfo: {},
      singleTable: [],
      dimVisible: false,
      groupVisible: false,
      tabsType: '1'
    })
    const dimModelRef = ref()
    const devcolumns: TableColumnProps<FormValuesTypeDev>[] = [
      {
        label: '设备名称',
        prop: 'name',
        minWidth: 180,
        align: 'center',
        showOverflowTooltip: true,
        disabled: true
      },
      {
        label: '设备编号',
        prop: 'code',
        minWidth: 180,
        align: 'center',
        showOverflowTooltip: true,
        disabled: true
      },
      {
        label: '设备型号',
        prop: 'modelName',
        minWidth: 160,
        align: 'center',
        showOverflowTooltip: true
      }
    ]
    const columns: TableColumnProps<FormValuesType>[] = [
      {
        label: '单灯名称',
        prop: 'lampNodeName',
        minWidth: 100,
        align: 'center',
        showOverflowTooltip: true,
        disabled: true
      },
      {
        label: '回路',
        prop: 'num',
        minWidth: 50,
        align: 'center',
        unFixed: true,
        showOverflowTooltip: true,
        disabled: true
      },
      {
        label: '开关',
        prop: 'switchStatus',
        minWidth: 50,
        align: 'center',
        unFixed: true,
        showOverflowTooltip: true,
        disabled: true,
        render: ({ row }) => (
          <div
            class={styles.lightIcon}
            style={
              row.switchStatus === '1' ? 'background-color: #f85151;' : 'background-color: #a1a1a1'
            }
          ></div>
        )
      },
      {
        label: '电压',
        prop: 'dcVoltage',
        minWidth: 80,
        align: 'center',
        unFixed: true,
        showOverflowTooltip: true,
        disabled: true
      },
      {
        label: '电流',
        prop: 'dcCurrent',
        minWidth: 100,
        align: 'center',
        unFixed: true,
        showOverflowTooltip: true,
        disabled: true
      },
      {
        label: '调光',
        prop: 'dimmingLevel',
        minWidth: 100,
        align: 'center',
        unFixed: true,
        showOverflowTooltip: true,
        disabled: true
      },
      // {
      //   label: '有功电量',
      //   prop: 'activeEnergy',
      //   minWidth: 100,
      //   align: 'center',
      //   unFixed: true,
      //   showOverflowTooltip: true,
      //   disabled: true
      // },
      {
        label: '有功功率',
        prop: 'activePower',
        minWidth: 100,
        align: 'center',
        unFixed: true,
        showOverflowTooltip: true,
        disabled: true
      },
      {
        label: '漏电流',
        prop: 'leakageCurrent',
        minWidth: 80,
        align: 'center',
        unFixed: true,
        showOverflowTooltip: true,
        disabled: true
      }
    ]

    const webSocketRef = useWebsocket('/websocket/protocol/lampctrl', {
      // // 接收数据回调
      onmessage: () => {}
    })
    const userState = useVuexGetters('user', ['token'])
    const noticeRef = ref()
    const open = async (data: any) => {
      // 获取灯杆详情
      const res = await store.dispatch('singleLamp/GetPostDetail', { lampPostId: data.id })
      if (res.code === 200) {
        state.lamppostInfo = res.data
      }
      // 获取当日实时统计数据
      const res1 = await store.dispatch('singleLamp/DayEnergyData', { lampPostId: data.id })
      if (res1.code === 200) {
        state.realTimeData = res1.data
      }
      // 获取当日调光数据
      const res2 = await store.dispatch('singleLamp/DayDimData', { lampPostId: data.id })
      if (res2.code === 200) {
        state.dimData = {
          hour: res2.data.map((item: dimDataType) => item.hour),
          dim: res2.data.map((item: dimDataType) => item.dim)
        }
      }
      // 获取当日调光数据
      const res3 = await store.dispatch('singleLamp/EnergyData', { lampPostId: data.id })
      if (res3.code === 200) {
        const realData = res3.data.filter((el: any) => el.type === '1')
        const ratedData = res3.data.filter((el: any) => el.type === '0')
        state.energyData = {
          hour: realData.map((item: any) => item.hour),
          ratedEnergy: ratedData.map((item: any) => item.value),
          realEnergy: realData.map((item: any) => item.value)
        }
      }
    }
    const handleOption = (type: any, title: string) => {
      // opr : 1开 0关
      if (!state.lamppostInfo?.monitorLampNodeVOList.length) {
        ElMessage.warning('此灯杆没有绑定单灯')
        return
      }
      let text = ''
      let commandCodeValue = ''
      if (type === 1) {
        text = '确认下发开灯命令？'
        commandCodeValue = '004'
      } else if (type === 0) {
        text = '确认下发关灯命令？'
        commandCodeValue = '004'
      } else if (type === 3) {
        text = '确认下发召测命令？'
        commandCodeValue = '006'
      }
      ElMessageBox({
        title: '确认提示',
        message: (
          <section class={styles['delete-confirm-box']}>
            {<p class="delete-title">{text}</p>}
          </section>
        ),
        showCancelButton: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--primary is-plain',
        closeOnClickModal: false, // 点遮罩层不关弹窗
        draggable: true // 可拖拽
      })
        .then(async () => {
          if (type === 0 || type === 1) {
            await store.dispatch('singleLamp/LamppostSwitch', {
              lampPostId: state.lamppostInfo?.id,
              opr: type
            })
          } else if (type === 3) {
            await store.dispatch('singleLamp/LamppostPoll', {
              lampPostId: state.lamppostInfo?.id
            })
          }

          const arr = state.lamppostInfo?.monitorLampNodeVOList.filter((item: any) => item.id)
          const codes = state.lamppostInfo?.monitorLampNodeVOList.filter((item: any) => item.code)
          arr.forEach((element: any) => {
            const websockParams = {
              deviceId: element,
              commandCode: commandCodeValue,
              token: userState.token.value
            }
            webSocketRef.value!.send(JSON.stringify(websockParams))
          })
          noticeRef.value.initMes({
            deviceId: arr.join(','),
            commandCode: commandCodeValue,
            token: userState.token.value,
            title,
            key: commandCodeValue,
            arrStr: codes.join(','),
            callBack: () => {}
          })
        })
        .catch(() => {})
    }
    const swInitFun = (data?: any) => {
      if (data.result === '2') {
        noticeRef.value.stateFun({
          key: data.commandCode,
          state: 'error',
          errText: data.data.message || '命令下发失败！'
        })
        return false
      }
      // 单个回路
      if (data.data.status === 1)
        noticeRef.value.stateFun({
          key: data.commandCode,
          id: ''
        })
    }

    // 调光
    const dimLight = async () => {
      if (!state.lamppostInfo?.monitorLampNodeVOList.length) {
        ElMessage.warning('此灯杆没有绑定单灯')
        return
      }

      const dimNum = dimModelRef.value.ruleForm.dimNum
      const res = await store.dispatch('singleLamp/Lamppostdim', {
        lampPostId: state.lamppostInfo?.id,
        dim: dimNum
      })
      if (res.code === 200) {
        ElMessage({
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
        dimModelChange()
      }
      const arr = state.lamppostInfo?.monitorLampNodeVOList.filter((item: any) => item.id)
      const ids = arr.join(',')
      const codes = state.lamppostInfo?.monitorLampNodeVOList.filter((item: any) => item.code)
      arr.forEach((element: any) => {
        const websockParams = {
          deviceId: element.id,
          commandCode: '004',
          token: userState.token.value
        }
        webSocketRef.value!.send(JSON.stringify(websockParams))
      })
      noticeRef.value.initMes({
        deviceId: ids,
        commandCode: '004',
        token: userState.token.value,
        title: '调光',
        key: '004',
        arrStr: codes.join(','),
        callBack: () => {}
      })
    }
    const dimModelChange = () => {
      state.dimVisible = !state.dimVisible
    }
    // 更换分组
    const changeGroup = () => {
      state.groupVisible = !state.groupVisible
    }
    // 重新获取数据
    const refresh = async () => {
      props.initLamppostTree()
      const res = await store.dispatch('singleLamp/GetPostDetail', {
        lampPostId: state.lamppostInfo?.id
      })
      if (res.code === 200) {
        state.lamppostInfo = res.data
      }
    }

    // 合并单灯工况单元格
    let cellList: any[] = []
    let count = 0
    const computeCell = (tableList: FormValuesType[]) => {
      cellList = []
      count = 0
      for (let i = 0; i < tableList.length; i++) {
        if (i === 0) {
          cellList.push(1)
          count = 0
        } else {
          if (tableList[i].lampNodeName === tableList[i - 1].lampNodeName) {
            cellList[count] += 1
            cellList.push(0)
          } else {
            cellList.push(1)
            count = 1
          }
        }
      }
    }
    const sortArray = (x: any, y: any) => {
      if (x.lampNodeName < y.lampNodeName) {
        return -1
      } else if (x.lampNodeName > y.lampNodeName) {
        return 1
      } else {
        return 0
      }
    }
    //  合并单元格
    const arraySpanMethod = ({
      // row,
      // column,
      rowIndex,
      columnIndex
    }: SpanMethodProps) => {
      computeCell(state.lamppostInfo?.workInfoItemList.sort(sortArray))
      if (columnIndex === 0) {
        const fRow = cellList[rowIndex]
        const fCol = fRow > 0 ? 1 : 0
        return {
          rowspan: fRow,
          colspan: fCol
        }
      } else {
        return {
          rowspan: 1,
          colspan: 1
        }
      }
    }

    expose({ open })

    onMounted(async () => {
      window.swInitFun = swInitFun
    })
    return () => (
      <section style="animation: animate-cloud 0.55s ease-out;">
        <div class={styles.lamppostRight}>
          <div class={styles.lampTitle}>
            <div class={styles.lineTxt}>{state.lamppostInfo?.name}</div>
            <div>
              <ElLink type="primary" underline={false} onClick={props.cancel}>
                <AliIcon type="icon-danchuang-guanbi" color="#fff" />
              </ElLink>
            </div>
          </div>
          <div class={styles.content}>
            <div class={styles.option}>
              <ElButton onClick={() => handleOption(3, '召测')}>
                <ElImage src={callDataSrc} style="margin-right:4px" />
                召测
              </ElButton>
              <ElButton onClick={() => handleOption(1, '开灯')}>
                <ElImage src={openLightSrc} style="margin-right:4px" />
                开灯
              </ElButton>
              <ElButton onClick={() => handleOption(0, '关灯')}>
                <ElImage src={closeLightSrc} style="margin-right:4px" />
                关灯
              </ElButton>
              <ElButton onClick={dimModelChange}>
                <ElImage src={dimLightSrc} style="margin-right:4px" />
                调光
              </ElButton>
              <ElButton onClick={changeGroup}>
                <ElImage src={changeGroupSrc} style="margin-right:4px" />
                更换分组
              </ElButton>
            </div>

            <div class={styles.baseInfo}>
              <div>
                <ElRow>
                  <ElCol span={12}>灯杆名称：{state.lamppostInfo?.name}</ElCol>
                  <ElCol span={12}>回路数量：{state.lamppostInfo?.num}</ElCol>
                </ElRow>
                <ElRow>
                  <ElCol span={12}>分组名称：{state.lamppostInfo?.groupName}</ElCol>
                </ElRow>
              </div>
              <ElTabs v-model={state.tabsType}>
                <ElTabPane label="基础设备数据" name="1">
                  <div style="margin:8px 0">
                    <div class={styles.title}></div>单灯设备数据
                  </div>
                  <ProSaasTable<FormValuesTypeDev>
                    tableId="monitor_devdata"
                    columns={devcolumns}
                    data={state.lamppostInfo?.monitorLampNodeVOList}
                    needPagination={false}
                  />
                  <div style="margin:8px 0;display:flex;align-items:center">
                    <div class={styles.title}></div>单灯工况数据
                    <div onClick={refresh} style="padding-left:4px;display:flex">
                      <ElIcon>
                        <Refresh />
                      </ElIcon>
                    </div>
                  </div>
                  <ProSaasTable<FormValuesType>
                    tableId="monitor_workdata"
                    columns={columns}
                    spanMethod={arraySpanMethod}
                    data={state.lamppostInfo?.workInfoItemList}
                    needPagination={false}
                  />
                </ElTabPane>
                <ElTabPane label="灯杆统计数据" name="2">
                  <ElDescriptions column={2}>
                    <ElDescriptionsItem label="在线率">
                      {state.realTimeData?.onlineRate}
                    </ElDescriptionsItem>
                    <ElDescriptionsItem label="额定电量">
                      {state.realTimeData?.sumRatedPower}
                    </ElDescriptionsItem>
                    <ElDescriptionsItem label="总用电量">
                      {state.realTimeData?.sumPower}
                    </ElDescriptionsItem>
                    <ElDescriptionsItem label="节省电量">
                      {state.realTimeData?.economizePower}
                    </ElDescriptionsItem>
                    <ElDescriptionsItem label="日节能率">
                      {state.realTimeData?.economizeRate}
                    </ElDescriptionsItem>
                    <ElDescriptionsItem label="日报警数">
                      {state.realTimeData?.alarmNum}
                    </ElDescriptionsItem>
                  </ElDescriptions>
                  {state.tabsType === '2' && (
                    <EchartsDim dataList={state.dimData} id="contents"></EchartsDim>
                  )}
                  {state.tabsType === '2' && (
                    <EchartsEnergy dataList={state.energyData} id="energy"></EchartsEnergy>
                  )}
                </ElTabPane>
              </ElTabs>
            </div>
          </div>
        </div>
        {state.dimVisible && (
          <DimModel ref={dimModelRef} onSubmitForm={dimLight} cancel={dimModelChange} />
        )}
        {state.groupVisible && (
          <ChangeGroup
            lampPostId={state.lamppostInfo?.id}
            cancel={changeGroup}
            onSubmitForm={refresh}
          />
        )}
        <NoticeMes ref={noticeRef} />
      </section>
    )
  }
})
